import os
import time
import requests
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from multiprocessing import Process
from driver.MyDriver import open_chrome_dr
from selenium.webdriver.support import expected_conditions as EC


# 根据链接下载旋转图片
def get_img(url):
    header = {
        "Host": "passport.baidu.com",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:93.0) Gecko/20100101 Firefox/93.0",
        "Accept": "image/avif,image/webp,*/*",
        "Accept-Language": "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2",
        "Accept-Encoding": "gzip, deflate, br",
        "Referer": "https://wappass.baidu.com/",
        "Connection": "keep-alive",
        "Cookie": 'Hm_lvt_3eecc7feff77952670b7c24e952e8773=1666849322,1666919008,1666961940,1667175865; Hm_lpvt_3eecc7feff77952670b7c24e952e8773=1667186488; token="MTY2NzE4NzczNS4yMTEzMjg1OmQwNDNhNmZiZTA4MjlmOGY1YjE0MjA0NmViN2M1NTdkM2MyYWY3NzE="; sessionid=aa6zibdmfbs5cwzh6x62niw7fbqe5pon',
        "Sec-Fetch-Dest": "image",
        "Sec-Fetch-Mode": "no-cors",
        "Sec-Fetch-Site": "same-site",
        "Pragma": "no-cache",
        "Cache-Control": "no-cache",
    }
    response = requests.get(url=url, headers=header)

    if response.status_code == 200:
        with open("images/" + str(int(time.time())) + ".jpg", 'wb') as f:
            f.write(response.content)
            f.close()


def main():
    driver = open_chrome_dr()
    driver.implicitly_wait(5)

    while True:
        # 访问百度首页
        driver.get('https://wappass.baidu.com/static/captcha/tuxing.html?&ak=c27bbc89afca0463650ac9bde68ebe06&backurl=https%3A%2F%%2Fs%3Fcl%3D3%26tn%3Dbaidutop10%26fr%3Dtop1000%26wd%3D%25E6%25B6%2588%25E9%2598%25B2%25E6%2588%2598%25E5%25A3%25AB%25E8%25BF%259E%25E5%25A4%259C%25E7%25AD%2591%25E5%259D%259D%25E5%25BA%2594%25E5%25AF%25B9%25E6%25B4%25AA%25E5%25B3%25B0%25E8%25BF%2587%25E5%25A2%2583%26rsv_idx%3D2%26rsv_dl%3Dfyb_n_homepage%26hisfilter%3D1&logid=8309940529500911554&signature=4bce59041938b160b7c24423bde0b518×tamp=1624535702')

        time.sleep(2)

        WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.CSS_SELECTOR, 'div.passMod_slide-btn.passMod_slide-btn-loading'))
        )

        time.sleep(2)
        # 等待验证码出现
        img = WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.CSS_SELECTOR, 'img.passMod_spin-background'))
        )
        img_src = img.get_attribute('src')

        # 下载图片
        get_img(img_src)


if __name__ == '__main__':
    # 多进程下载百度旋转验证码图片
    if not os.path.exists('images'):
        os.mkdir('images')

    process_num = 5

    for i in range(process_num):
        print(f'进程{i}启动')
        p = Process(target=main, name=f"work_{i}")
        p.start()
